import {
  list
} from '../../api/product'

import {
  list as designerList
} from '../../api/designer'

import {
  lockSysUser,
  scaner
} from '../../api/member'

import {
  qscaner, scaner as scanerLogin
} from '../../api/qrcode'

import {
  getHome
} from '../../api/wxPage'

import {
  getMchInfo
} from '../../api/amap'
import {
  getInfo
} from '../../api/enterprise'
import {
  popScreen,
  clickAndGet
} from '../../api/promotion'


const util = require('../../utils/util.js')
const app = getApp()
Page({
  data: {
    length: '',
    productPage: 20,
    isShow: true,
    pageId: 1,
    productList: [],
    signInList: [],
    pageNum: 0,
    isSwiperShow: true,
    pageSize: 10,
    componentsList: [],
    startSwipers: false,
    secondSwipers: false,
    thirdSwipers: false,
    fourthSwipers: false,
    fifthSwipers: false,
    lastTime: null,
    mchId: null,
    loading: false,
    shareImage: "",
    shareDescr: "",
    newPromotion: false,
    promotionForm: null,
    timestamp: Date.parse(new Date()),
    tabbarHeight: app.globalData.tabbarHeight,
    showBackTop: false
  },
  setNavSize: function () {
    var that = this,
      sysinfo = wx.getSystemInfoSync(),
      statusHeight = sysinfo.statusBarHeight,
      isiOS = sysinfo.system.indexOf('iOS') > -1,
      navHeight;
    console.log(sysinfo)
    if (!isiOS) {
      navHeight = 46;
    } else {
      navHeight = 42;
    }
    that.setData({
      status: statusHeight,
      navHeight: navHeight
    })
  },
  onBackTop() {
    wx.pageScrollTo({
      scrollTop: 0, // 滚动到的位置（距离顶部 px）
      duration: 500 //滚动所需时间 如果不需要滚动过渡动画，设为0（ms）
    })
  },
  onPageScroll: function (e) {
    this.setData({
      showBackTop: e.scrollTop > 100,
    })
    if (e.scrollTop > 217) {
      this.data.isSwiperShow = false
    } else {
      this.data.isSwiperShow = true
    }
    this.setData({
      isSwiperShow: this.data.isSwiperShow
    })

    let scrollTop = e.scrollTop * app.globalData.rpxR
    if (scrollTop >= 0 && scrollTop < 100) this.data.opacity = 1;
    else if (scrollTop >= 100 && scrollTop < 130) this.data.opacity = 0.9;
    else if (scrollTop >= 130 && scrollTop < 180) this.data.opacity = 0.8;
    else if (scrollTop >= 180 && scrollTop < 230) this.data.opacity = 0.7;
    else if (scrollTop >= 230 && scrollTop < 280) this.data.opacity = 0.5;
    else if (scrollTop >= 280 && scrollTop < 330) this.data.opacity = 0.4;
    else if (scrollTop >= 330 && scrollTop < 380) this.data.opacity = 0.3;
    else if (scrollTop >= 380 && scrollTop < 400) this.data.opacity = 0.2;
    else if (scrollTop >= 400 && scrollTop < 450) this.data.opacity = 0;
    else if (scrollTop >= 450) this.data.opacity = 0;

    this.data.componentsList.map(item => {
      if (item.name == 'swipersTranslate') {
        this.selectComponent('#swipersTranslate').changeOpacity(this.data.opacity)
      }
      
      if (item.name == 'swipers') {
        if (e.scrollTop == 0) {
          this.selectComponent('#swipers').resetClick();
        }
        if (e.scrollTop >= 40 && this.data.isShow == true) {
          this.selectComponent('#swipers').fifthClick();
          this.setData({
            isShow: false
          })
        } else if (e.scrollTop < 40 && this.data.isShow == false) {
          this.selectComponent('#swipers').fifthClick();
          this.setData({
            isShow: true
          })
        }
        if (e.scrollTop >= 5 && this.data.startSwipers == false) {
          this.selectComponent('#swipers').startClick();
          this.setData({
            startSwipers: true
          })
        } else if (e.scrollTop < 5 && this.data.startSwipers == true) {
          this.selectComponent('#swipers').startClick();
          this.setData({
            startSwipers: false
          })
        }
        if (e.scrollTop >= 15 && this.data.secondSwipers == false) {
          this.selectComponent('#swipers').secondClick();
          this.setData({
            secondSwipers: true
          })
        } else if (e.scrollTop < 15 && this.data.secondSwipers == true) {
          this.selectComponent('#swipers').secondClick();
          this.setData({
            secondSwipers: false
          })
        }
        if (e.scrollTop >= 25 && this.data.thirdSwipers == false) {
          this.selectComponent('#swipers').thirdClick();
          this.setData({
            thirdSwipers: true
          })
        } else if (e.scrollTop < 25 && this.data.thirdSwipers == true) {
          this.selectComponent('#swipers').thirdClick();
          this.setData({
            thirdSwipers: false
          })
        }


        if (e.scrollTop >= 35 && this.data.fourthSwipers == false) {
          this.selectComponent('#swipers').fourthClick();
          this.setData({
            fourthSwipers: true
          })
        } else if (e.scrollTop < 35 && this.data.fourthSwipers == true) {
          this.selectComponent('#swipers').fourthClick();
          this.setData({
            fourthSwipers: false
          })
        }
      }
    })
  },
  onPullDownRefresh() {
    var _this = this
    wx.showNavigationBarLoading()
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      _this.data.componentsList.forEach(item => {
        if (item.name === 'products') {
          _this.selectComponent('#products').downRefresh();
        } else if (item.name === 'productRow') {
          _this.selectComponent('#productRow').downRefresh();
        } else if (item.name === 'groupProduct') {
          _this.selectComponent('#groupProduct').downRefresh();
        } else if (item.name === 'conciseProductRow') {
          _this.selectComponent('#conciseProductRow').downRefresh();
        } else if (item.name === 'conciseProduct') {
          _this.selectComponent('#conciseProduct').downRefresh();
        } else if (item.name === 'groupProductRow') {
          _this.selectComponent('#groupProductRow').downRefresh();
        } else if (item.name === 'bargainProduct') {
          _this.selectComponent('#bargainProduct').downRefresh();
        } else if (item.name === 'bargainProductRow') {
          _this.selectComponent('#bargainProductRow').downRefresh();
        } else if (item.name === 'shopDetail') {
          _this.selectComponent('#shopDetail').downRefresh();
        } else if (item.name === 'nearbyShops') {
          _this.selectComponent('#nearbyShops').downRefresh();
        } else if (item.name === 'graphicList') {
          _this.selectComponent('#graphicList').downRefresh();
        }
      })

      wx.stopPullDownRefresh()
    }, 1000);
  },
  onReachBottom() {
    if (this.data.componentsList.length > 0) {
      if (this.data.componentsList[this.data.length - 1].name == 'products') {
        this.selectComponent('#products').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'productRow') {
        this.selectComponent('#productRow').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'groupProduct') {
        this.selectComponent('#groupProduct').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'conciseProductRow') {
        this.selectComponent('#conciseProductRow').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'conciseProduct') {
        this.selectComponent('#conciseProduct').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'groupProductRow') {
        this.selectComponent('#groupProductRow').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'bargainProduct') {
        this.selectComponent('#bargainProduct').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'bargainProductRow') {
        this.selectComponent('#bargainProductRow').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'shopDetail') {
        this.selectComponent('#shopDetail').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'groupCardList') {
        this.selectComponent('#groupCardList').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'nearbyShops') {
        this.selectComponent('#nearbyShops').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'graphicList') {
        this.selectComponent('#graphicList').onReachBottom();
      } else if (this.data.componentsList[this.data.length - 1].name == 'singleProducts') {
        this.selectComponent('#singleProducts').onReachBottom();
      }
    }
  },
  searchClick() {
    wx.navigateTo({
      url: '/pages/goods/search/index'
    })
  },
  startLockSysUser() {
    lockSysUser({
      mchId: app.globalData.mchId,
      xuid: app.globalData.xuid,
      shopId: app.globalData.shopId
    }).then(res => {
      console.log(res)
    })
  },
  onLoad: function (options) {
    let _this = this;
    if (!util.isNull(options.xuid)) {
      app.globalData.xuid = options.xuid;
    }
    if (!util.isNull(options.q)) {
      //扫码进入
      let s = decodeURIComponent(options.q);
      app.globalData.q = s
      if (s.indexOf('/q/88') == -1 && s.indexOf('/q/89') == -1) {
        if (s.indexOf('?productId') != -1) {
          let e = s.indexOf('?productId');
          let w = s.indexOf('/q/');
          let x = s.substring(w + 3, e);
          let d = s.substring(e + 11);
          app.globalData.xuid = x;
        } else if (s.indexOf('?groupBuyId') != -1) {
          let e = w = s.indexOf('?groupBuyId');
          let w = s.indexOf('/q/');
          let x = s.substring(w + 3, e);
          let d = s.substring(e + 12);
          app.globalData.xuid = x;
        } else {
          let w = s.indexOf('/q/');
          let x = s.substring(w + 3);
          app.globalData.xuid = x;
        }
      }
    }
    app.userInfoReadyCallback = res => {
      if (app.globalData.location == false && app.APP_TYPE == 1) {
        wx.navigateTo({
          url: '/pages/index/amap',
        })
      } else {
        _this.loadDesigner()
        this.data.timestamp = Date.parse(new Date());
        this.setData({
          timestamp: this.data.timestamp
        })
      }

      _this.setData({
        loading: app.globalData.loaded
      })

      app.event.emit("onCartChange");

      if (app.globalData.q != null) {
        _this.scanCodeClick()
      }

      _this.popScreenClick()

      util.forwarding(options, app.globalData.token)

    }

    this.setNavSize()
    // this.getGeoCode()

    //没有关闭小程序时，二次扫码要被调相关方法

    if (app.globalData.loaded == true) {

      //服务时，扫码

      if (app.globalData.q != null) {

        if (app.APP_TYPE > 0 && app.globalData.location == false) {

          getMchInfo({ xuid: app.globalData.xuid }).then(res => {
            if (res.data != null && res.data.sysMch != null) {
              app.globalData.mchId = res.data.sysMch.id
              app.globalData.mchName = res.data.sysMch.name
              app.globalData.location = res.data.locked;
              app.globalData.cityName = res.data.cityName
              if (res.data.shop != null) {
                app.globalData.shopId = res.data.shop.id
                app.globalData.shopName = res.data.shop.name
              }
              _this.loadDesigner()
              _this.scanCodeClick()

              util.forwarding(options, app.globalData.token)

            }

          }).catch(error => {
            console.log(error)
          })
        } else {
          _this.scanCodeClick()
          util.forwarding(options, app.globalData.token)
        }
      } else {
        util.forwarding(options, app.globalData.token)
      }
    }
    getInfo().then(res => {
      console.log(res.data);
      if (res.data.shippingConfig != '') {
        let shippingConfig = JSON.parse(res.data.shippingConfig)
        console.log(shippingConfig, 'shippingConfig', res.data.shippingConfig)
        app.DELIVERY_TIME = shippingConfig.deliveryTime ? 1 : 0
      }
      if (res.data) {
        
      }
    })
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    let _this = this
    if (app.APP_TYPE == 0) {
      this.loadDesigner()
      if (app.globalData.loaded == true) {
        this.popScreenClick()
      }
    } else
      if (app.globalData.location == true) {
        this.loadDesigner()
        if (app.globalData.loaded == true) {
          this.popScreenClick()
        }
      } else {
        if (this.data.loading) {
          wx.navigateTo({
            url: '/pages/index/amap',
          })
        }
      }
  },

  getHomeData() {
    getHome({
      "mchId": app.globalData.mchId
    }).then(res => {
      if (res.data.wxPage.hasOwnProperty('shareImage') && !util.isNull(res.data.wxPage.shareImage)) {
        this.data.shareImage = res.data.wxPage.shareImage
        this.setData({
          shareImage: res.data.wxPage.shareImage
        })
      }
      if (res.data.wxPage.hasOwnProperty('shareDescr') && !util.isNull(res.data.wxPage.shareDescr)) {
        this.data.shareDescr = res.data.wxPage.shareDescr
        this.setData({
          shareDescr: res.data.wxPage.shareDescr
        })
      }
    })
  },
  //加载设计器的数据
  loadDesigner() {
    let curTime = new Date().getTime();
    if (this.data.lastTime != null && app.globalData.mchId == this.data.mchId) {
      if (this.data.lastTime > (curTime - 1800)) {
        return;
      }
    }
    this.data.lastTime = curTime;

    designerList({
      mchId: app.globalData.mchId
    }).then(res => {
      console.info("设计起加载res--" + JSON.stringify(res))
      this.data.mchId = app.globalData.mchId;
      this.data.length = res.data.length
      this.data.componentsList = res.data
      this.setData({
        componentsList: this.data.componentsList,
      })
    })

    this.getHomeData()

  },
  onShareAppMessage: function () {
    let shareImage = util.isNull(this.data.shareImage) ? "" : util.thumbnail(this.data.shareImage, 500, 400)
    let shareDescr = util.isNull(this.data.shareDescr) ? app.globalData.mchName : this.data.shareDescr
    let userId = app.globalData.userInfo.id

    console.log(shareImage, 1111)
    return {
      title: shareDescr,
      desc: shareDescr,
      imageUrl: shareImage,
      path: '/pages/index/index?xuid=' + userId // 路径，传递参数到指定页面。
    }
  },
  onShareTimeline: function () {
    let shareImage = util.isNull(this.data.shareImage) ? "" : util.thumbnail(this.data.shareImage, 500, 400)
    let shareDescr = util.isNull(this.data.shareDescr) ? app.globalData.mchName : this.data.shareDescr
    let userId = util.isNull(this.data.userInfo) ? "" : app.globalData.userInfo.id
    return {
      title: shareDescr,
      desc: shareDescr,
      path: '/pages/index/index',
      imageUrl: shareImage,
      query: 'xuid=' + userId
    }
  },
  // 获取定位信息
  getGeoCode() {
    wx.getLocation({
      type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      isHighAccuracy: true,
      success: res => {
        app.globalData.lat = res.latitude
        app.globalData.lng = res.longitude
        app.event.emit('lat&lng', { lat: res.latitude, lng: res.longitude })
        app.getGeoCode(app.globalData.lat, app.globalData.lng).then(res => {
          app.globalData.address = res.data.address,
            app.globalData.cityName = res.data.areaName.substring(res.data.areaName.indexOf("省") + 1, res.data.areaName.indexOf("市") + 1),
            app.event.emit('getGeoCode', { data: res.data })
          this.loadDesigner()
        })
      },
      fail: err => {
        console.log(err)
      }
    })
    // }
  },
  //获取弹屏活动
  popScreenClick() {
    var _this = this
    popScreen({
      mchId: app.globalData.mchId
    }).then(res => {
      if (res.content != '无活动') {
        if (res.data.itemList.length > 0) {
          res.data.itemList.forEach(function (item) {
            item.endDate = _this.formatDateAndTime(item.endDate)
            item.tag = _this.formatTag(item.targetType)
          })
          _this.data.newPromotion = true
          _this.data.promotionForm = res.data
          _this.setData({
            newPromotion: _this.data.newPromotion,
            promotionForm: _this.data.promotionForm
          })
          console.log(_this.data.promotionForm, "12345")
        } else {
          _this.data.newPromotion = false
          _this.setData({
            newPromotion: _this.data.newPromotion
          })
        }
      } else {
        _this.data.newPromotion = false
        _this.setData({
          newPromotion: _this.data.newPromotion
        })
      }
    })
  },
  canclePromotion() {
    var _this = this
    _this.data.newPromotion = false
    _this.setData({
      newPromotion: _this.data.newPromotion
    })
  },
  formatTag(value) {
    let rusult = ""
    switch (value) {
      case 0:
        rusult = "全场通用"
        break;
      case 1:
        rusult = "指定品牌"
        break;
      case 2:
        rusult = "会员专属"
        break;
      case 3:
        rusult = "指定品类"
        break;
      case 4:
        rusult = "指定商品"
        break;
      case 5:
        rusult = "指定商品兑换"
        break;
    }
    return rusult
  },
  //时间格式化器
  formatDateAndTime: function (value) {
    let date = new Date(value);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();
    return y + '-' + MM + '-' + d + " " + h + ":" + m + ":" + s;
  },
  clickAndGetClick() {
    var _this = this
    if (app.globalData.token == null) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
      return;
    }
    clickAndGet({
      promotionId: _this.data.promotionForm.promotion.id
    }).then(res => {
      console.log(res)
      _this.data.newPromotion = false
      _this.setData({
        newPromotion: _this.data.newPromotion
      })
      wx.navigateTo({
        url: '/pages/member/coupon/coupon',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },
  scanCodeClick() {
    var _this = this
    if (app.globalData.token == null) {
      wx.navigateTo({
        url: '/pages/login/index?cardType=true',
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromOpenedPage: function (data) {
            if (data.cardType == 'true') {
              _this.topUpClick()
            }
          },
        },
      })
    } else {
      _this.topUpClick()
    }
  },
  topUpClick() {
    var _this = this
    if (!util.isNull(app.globalData.q)) {
      var s = app.globalData.q
      if (s.indexOf('/q/88') != -1) {
        scaner({
          q: app.globalData.q
        }).then(res => {
          wx.showModal({
            title: '提示',
            content: res.content,
            cancelText: '去购物',
            confirmText: '去查看',
            success(resd) {
              if (resd.confirm) {
                console.log('用户点击确定')
                _this.shopCardClick()
              } else if (resd.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        })
      } else if (s.indexOf('/q/89') != -1) {
        qscaner({
          q: app.globalData.q
        }).then(res => {
          wx.showModal({
            title: '提示',
            content: res.content,
            cancelText: '去购物',
            confirmText: '去查看',
            success(resd) {
              if (resd.confirm) {
                console.log('用户点击确定')
                _this.couponClick()
              } else if (resd.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        })
      } else if (s.indexOf('/q/90') != -1) {
        //扫码自动登录
        _this.scanerClick(app.globalData.q)
      } else {
        _this.startLockSysUser()
        _this.jumpTo()
      }
    }
  },
  jumpTo() {
    let s = app.globalData.q;
    if (s == null) {
      return;
    }
    if (s.indexOf('/q/88') == -1 && s.indexOf('/q/89') == -1) {
      if (s.indexOf('?productId') != -1) {
        let e = s.indexOf('?productId');
        let w = s.indexOf('/q/');
        let x = s.substring(w + 3, e);
        let d = s.substring(e + 11);
        app.globalData.xuid = x;
        wx.navigateTo({
          url: '/pages/goods/product/details?id=' + d,
        })
      } else if (s.indexOf('?groupBuyIds') != -1) {
        let codeRegExp = ('groupBuyIds=(\\S*)')  //跳多人拼团页面
        let id = s.split('&')[0].match(codeRegExp)[1]
        let codeRegExps = ('obj=(\\S*)')
        let obj = s.split('&')[1].match(codeRegExps)[1]
        wx.navigateTo({
          url: '/pages/goods/product/groupBuydetails?id=' + id + '&obj=' + obj,
        })
      } else if (s.indexOf('?groupBuyId') != -1) {
        let e = w = s.indexOf('?groupBuyId');
        let w = s.indexOf('/q/');
        let x = s.substring(w + 3, e);
        let d = s.substring(e + 12);
        app.globalData.xuid = x;
        wx.navigateTo({
          url: '/pages/goods/product/groupDetails?id=' + d,
        })
      } else if (s.indexOf('?shopId') != -1) {
        let e = w = s.indexOf('?shopId');
        let w = s.indexOf('/q/');
        let x = s.substring(w + 3, e);
        let d = s.substring(e + 12);
        app.globalData.xuid = x;
        let url = s
        var reg = new RegExp('(^|&)' + 'shopId' + '=([^&]*)(&|$)', 'i')
        var r = url.slice(url.indexOf('?') + 1).match(reg)
        let shopId = r[2]
        wx.navigateTo({
          url: '/pages/goods/order/order?id=' + shopId,
        })
      }
    }
  },

  shopCardClick() {
    wx.navigateTo({
      url: '/pages/member/shopCard/shopCard',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  couponClick() {
    wx.navigateTo({
      url: '/pages/member/coupon/coupon',
    })
  },

  jumpDeatil() {
    wx.navigateTo({
      url: '/pages/goods/shopDetail/shopDetail'
    })
  },
  //扫码自动登录
  scanerClick(data) {
    var _this = this
    scanerLogin({ mchId: app.globalData.mchId, isvId: app.isvId, q: data }).then(res => {
      if (res.type == 'success') {
        const {
          userInfo,
          userId,
          token
        } = res.data
        app.globalData.uuid = userId
        app.globalData.token = token
        app.globalData.userInfo = userInfo
        app.QRCODELOGIN = true

        if (app.APP_TYPE > 0) {
          getMchInfo({ xuid: app.globalData.xuid }).then(res => {
            if (res.data != null && res.data.sysMch != null) {
              app.globalData.mchId = res.data.sysMch.id
              app.globalData.mchName = res.data.sysMch.name
              app.globalData.cityName = res.data.cityName
              app.globalData.location = res.data.locked;
            }
            app.globalData.loaded = true;

            if (app.SCOPE_TYPE == 2) {
              wx.switchTab({
                url: '/pages/tabBar/water/water'
              })
            } else {
              wx.switchTab({
                url: '/pages/index/index'
              })
            }

          }).catch(error => {
            console.log(error)
          })

        } else {

          app.globalData.location = true;
          app.globalData.loaded = true;

          if (app.SCOPE_TYPE == 2) {
            wx.switchTab({
              url: '/pages/tabBar/water/water'
            })
          } else {
            wx.switchTab({
              url: '/pages/index/index'
            })
          }
        }
      }
    }).catch(error => {
      wx.showToast({
        title: error.content,
        icon: 'none',
        duration: 2000
      })
    })
  }
})
